package com.bishe.app.core.utils;

import org.springframework.core.io.ClassPathResource;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * Created : 2024/6/25, 15:47
 *
 * @author : jeffrey.hu
 **/
public class ImgUtils {

    public static BufferedImage img(String[][] tableData) throws Exception {
        // 单元格宽度和高度
        int cellWidth = 100;
        int cellHeight = 40;

        int width = cellWidth * tableData[0].length + 30;
        int height = cellHeight + 100;

        Color backgroundColor = Color.WHITE;  // 背景颜色

        // 创建一个BufferedImage对象作为画布
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 获取画布的Graphics2D对象
//        Graphics2D g2d = image.createGraphics();

//字体
        ClassPathResource fontResource = new ClassPathResource("msyh.ttc");
// 设置文字
        Font font = Font.createFont(Font.TRUETYPE_FONT, fontResource.getInputStream());
        font = font.deriveFont(Font.BOLD, 16F);
        Font multiFont = font.deriveFont(Font.BOLD, 16f);
        Font finalfont = font.deriveFont(Font.PLAIN, 16f);
        GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
        localGraphicsEnvironment.registerFont(font);
        localGraphicsEnvironment.registerFont(multiFont);
        localGraphicsEnvironment.registerFont(finalfont);
// 开启画图
        Graphics2D g2d = localGraphicsEnvironment.createGraphics(image);
//设置字体
        g2d.setFont(font);
//这里就是大小为64F的字体
        g2d.setFont(multiFont);
//这里就是大小为60f的字体
        g2d.setFont(finalfont);

        // 设置抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 设置背景颜色并清空画布
        g2d.setColor(backgroundColor);
        g2d.fillRect(0, 0, width, height);


        // 表格起始xy坐标
        int startX = 0 + 10;
        int startY = 0 + 40;


        // 绘制表格
        g2d.setColor(Color.BLACK);
        for (int row = 0; row < tableData.length; row++) {
            for (int col = 0; col < tableData[row].length; col++) {
                int x = startX + col * cellWidth;
                int y = startY + row * cellHeight;

                // 绘制单元格边框
                g2d.drawRect(x, y, cellWidth, cellHeight);

                // 绘制单元格内容
                g2d.drawString(tableData[row][col], x + 10, y + 25); // 文字位置微调
            }
        }

        // 释放Graphics2D对象
        g2d.dispose();

        return image;
    }
}

